﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Services
{
	using Falcon.Core.Authentication;
	using Falcon.Core.Authorization;
	using Falcon.Core.Domain.Services;
	using UserIdentity = Falcon.Core.Domain.UserIdentity;

	public class WebIdentityService : IIdentityService
	{
		/// <summary>
		/// Gets a value indicating whether this instance is authenticated.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is authenticated; otherwise, <c>false</c>.
		/// </value>
		public bool IsAuthenticated
		{
			get
			{
				var current = this.Current;

				return current != null && current.IsAuthenticated;
			}
		}

		/// <summary>
		/// Gets a value indicating whether this instance is privileged.
		/// </summary>
		/// <value>
		/// 	<c>true</c> if this instance is privileged; otherwise, <c>false</c>.
		/// </value>
		public bool IsPrivileged
		{
			get
			{
				var current = this.Current;

				return current != null && (current.IsAdministrator || current.IsModerator);
			}
		}

		/// <summary>
		/// Gets the current user identity.
		/// </summary>
		/// <value>The current user identity.</value>
		public UserIdentity Current
		{
			get
			{
				var identity = GetIdentity();

				if (identity == null)
				{
					return null;
				}

				return new UserIdentity
				{
					Id = identity.Id,
					IsAuthenticated = identity.IsAuthenticated,
					IsAdministrator = identity.IsAdministrator,
					IsModerator = identity.IsModerator,
					Session = identity.Session
				};
			}
		}

		/// <summary>
		/// Gets the identity.
		/// </summary>
		/// <returns></returns>
		private static WebUserIdentity GetIdentity()
		{
			var principal = PermissivePrincipalPermission.Current as WebPermissivePrincipal;

			if (principal == null)
			{
				return null;
			}

			return principal.Identity as WebUserIdentity;
		}
	}
}